from flask import Blueprint, jsonify, request, redirect
from models import db, Bill
from datetime import datetime, timedelta
from collections import defaultdict
import calendar
import random

def get_random_color():
    """生成随机颜色"""
    return f'rgb({random.randint(0, 255)}, {random.randint(0, 255)}, {random.randint(0, 255)})'

bp = Blueprint('api', __name__)

@bp.route('/api/bills/stats', methods=['GET'])
def get_stats():
    """获取统计数据的API"""
    period = request.args.get('period', 'day')  # day/month/year
    date_str = request.args.get('date')  # YYYY-MM-DD
    
    try:
        date = datetime.strptime(date_str, '%Y-%m-%d') if date_str else None
    except:
        date = None
    
    if not date and period == 'day':
        # 按日统计默认使用最新日期
        latest_bill = Bill.query.order_by(Bill.date.desc()).first()
        if latest_bill:
            date = latest_bill.date
            # 确保返回的日期格式与前端一致
            return redirect(f'/api/bills/stats?period=day&date={date.strftime("%Y-%m-%d")}')
        date = datetime.now()
    elif not date:
        date = datetime.now()
    
    # 根据时间段筛选数据
    if period == 'day':
        start = datetime(date.year, date.month, date.day)
        end = start + timedelta(days=1)
    elif period == 'month':
        start = datetime(date.year, date.month, 1)
        end = datetime(date.year, date.month, calendar.monthrange(date.year, date.month)[1]) + timedelta(days=1)
    elif period == 'year':
        start = datetime(date.year, 1, 1)
        end = datetime(date.year + 1, 1, 1)
    else:
        return jsonify({'error': 'Invalid period'}), 400
    
    bills = Bill.query.filter(Bill.date >= start, Bill.date < end).all()
    
    # 计算统计数据
    income = sum(b.amount for b in bills if b.type == '收入')
    expense = sum(b.amount for b in bills if b.type == '支出')
    balance = income + expense  # 支出为负值
    
    # 按类别和二级分类统计
    income_by_category = defaultdict(float)
    expense_by_category = defaultdict(float)
    income_by_subcategory = defaultdict(float)
    expense_by_subcategory = defaultdict(float)
    daily_stats = get_daily_stats(bills, period, date) if period != 'day' else None
    for bill in bills:
        if bill.type == '收入':
            income_by_category[bill.category] += bill.amount
            if bill.subcategory:
                income_by_subcategory[bill.subcategory] += bill.amount
        else:
            expense_by_category[bill.category] += bill.amount
            if bill.subcategory:
                expense_by_subcategory[bill.subcategory] += bill.amount

    
    return jsonify({
        'period': period,
        'date': date.strftime('%Y-%m-%d'),
        'income': income,
        'expense': -expense,  # 支出转为正数
        'balance': balance,
        'income_by_category': dict(income_by_category),
        'expense_by_category': dict(expense_by_category),
        'income_by_subcategory': dict(income_by_subcategory),
        'expense_by_subcategory': dict(expense_by_subcategory),
        'daily_stats': daily_stats,
        'bills': [{
            'id': b.id,
            'date': b.date.strftime('%Y-%m-%d %H:%M'),
            'type': b.type,
            'amount': b.amount,
            'category': b.category,
            'subcategory': b.subcategory,
            'account': b.account,
            'remark': b.remark
        } for b in bills]
    })

@bp.route('/api/bills/months', methods=['GET'])
def get_months():
    """获取所有账单月份"""
    months = db.session.query(
        db.func.strftime('%Y-%m', Bill.date).label('month')
    ).distinct().order_by(db.desc('month')).all()
    return jsonify([m.month for m in months])

@bp.route('/api/bills/list', methods=['GET'])
def get_daily_stats(bills, period, date):
    """获取每日/月统计数据"""
    daily_data = defaultdict(lambda: defaultdict(float))
    
    for bill in bills:
        day = bill.date.day if period == 'month' else bill.date.month
        if bill.type == '收入':
            if bill.subcategory:
                daily_data[day][bill.subcategory] += bill.amount
        else:
            daily_data[day][bill.category] += bill.amount
    
    # 转换为前端需要的格式
    result = {
        'labels': sorted(daily_data.keys()),
        'income_datasets': [],
        'expense_datasets': []
    }
    
    # 收集所有二级分类（收入）和类别（支出）
    all_subcategories = set()
    all_categories = set()
    for day in daily_data:
        for key in daily_data[day]:
            # 通过金额正负判断是收入还是支出
            if daily_data[day][key] > 0:
                all_subcategories.add(key)
            else:
                all_categories.add(key)
    
    # 生成收入数据集（按二级分类）
    for subcategory in all_subcategories:
        result['income_datasets'].append({
            'label': subcategory,
            'data': [daily_data[day].get(subcategory, 0) for day in result['labels']],
            'borderColor': get_random_color(),
            'tension': 0.1
        })
    
    # 生成支出数据集（按类别）
    for category in all_categories:
        result['expense_datasets'].append({
            'label': category,
            'data': [abs(daily_data[day].get(category, 0)) for day in result['labels']],  # 支出转为正数
            'borderColor': get_random_color(),
            'tension': 0.1
        })
    
    return result

def get_bills():
    """获取账单列表的API"""
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 20))
    
    query = Bill.query.order_by(Bill.date.desc())
    pagination = query.paginate(page=page, per_page=per_page)
    
    return jsonify({
        'bills': [{
            'id': b.id,
            'date': b.date.strftime('%Y-%m-%d %H:%M'),
            'type': b.type,
            'amount': b.amount,
            'category': b.category,
            'subcategory': b.subcategory,
            'account': b.account,
            'remark': b.remark
        } for b in pagination.items],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': pagination.page
    })